package com.xbai.security.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xbai.security.entity.Menu;
import com.xbai.security.entity.Role;
import com.xbai.security.entity.Users;
import com.xbai.security.mapper.UserInfoMapper;
import com.xbai.security.mapper.UsersMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xbai
 * @Date 2021/4/18
 */
@Service("userDetailsService")
@Slf4j
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
       /* if (!"lisi".equals(username)) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        String password = passwordEncoder.encode("123456");
        List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("role");
        return new User("lisi", password, auths);*/

        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        Users users = usersMapper.selectOne(wrapper);
        if (users == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        // 获取到用户角色，菜单列表
        List<Role> roleList = userInfoMapper.selectRoleByUserId(users.getId());
        List<Menu> menuList = userInfoMapper.selectMenuByUserId(users.getId());

        List<GrantedAuthority> auths = new ArrayList<>();
        // 处理角色
        roleList.forEach(role -> {
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority("ROLE_" + role.getName());
            auths.add(authority);
        });
        // 处理权限
        menuList.forEach(menu -> auths.add(new SimpleGrantedAuthority(menu.getPermission())));
        return new User(users.getUsername(), users.getPassword(), auths);
    }
}
